package monster.com.cvh.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import monster.com.cvh.R;
import monster.com.cvh.activity.AboutActivity;
import monster.com.cvh.activity.CollectionActivity;
import monster.com.cvh.activity.FeedbackActivity;
import monster.com.cvh.activity.LoginActivity;
import monster.com.cvh.activity.LookedActivity;
import monster.com.cvh.activity.MessageNoticeActivity;
import monster.com.cvh.activity.SettingActivity;
import monster.com.cvh.activity.UserInfoActivity;
import monster.com.cvh.bean.GetNotifyStatusBean;
import monster.com.cvh.bean.GetUserInfoBean;
import monster.com.cvh.bean.PostBean;
import monster.com.cvh.fragment.base.PermissionFragment;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.NetworkUtil;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

/**
 * 我的界面
 * Created by ASUS on 2017/11/11.
 */

public class MyFragment extends PermissionFragment {
    private static final int INFO_CODE = 1201;
    Unbinder unbinder;
    @BindView(R.id.rl_fragment_my_message_notice)
    RelativeLayout rlmRlFragmentMyMessageNotice;
    @BindView(R.id.rl_fragment_my_collection)
    RelativeLayout mRlFragmentMyCollection;
    @BindView(R.id.rl_fragment_my_about)
    RelativeLayout mRlFragmentMyAbout;
    @BindView(R.id.rl_fragment_my_setting)
    RelativeLayout mRlFragmentMySetting;
    @BindView(R.id.rl_fragment_my_see)
    RelativeLayout mRlFragmentMySee;
    @BindView(R.id.rl_fragment_my_feedback)
    RelativeLayout mRlFragmentMyFeedback;
    @BindView(R.id.tv_summary)
    TextView tvSummary;
    @BindView(R.id.tv_user_fragment_name)
    TextView mTvUserFragmentName;
    @BindView(R.id.tv_fragment_my_id)
    TextView mTvFragmentMyId;
    @BindView(R.id.sc_fragment_my)
    SwitchCompat scFragmentMy;
    @BindView(R.id.iv_user_fragment_avatar)
    CircleImageView mIvUserFragmentAvatar;
    @BindView(R.id.tv_fragment_copy)
    TextView mTvFragmentCopy;
    @BindView(R.id.tv_fragment_my_login)
    TextView tvFragmentMyLogin;
    @BindView(R.id.rl_fragment_my_user_info)
    RelativeLayout rlFragmentMyUserInfo;
    @BindView(R.id.iv_about)
    ImageView ivAbout;
    @BindView(R.id.smartRefreshLayout_fragment_my)
    SmartRefreshLayout mSmartRefreshLayoutFragmentMy;
    private String token;
    private ProgressDialog mDialog;

    @SuppressLint("SetTextI18n")
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        token = SPUtils.getString(getActivity(), "token", "");


    }

    @Override
    public void onResume() {
        super.onResume();
        checkNetWork();
    }

    /**
     * 检查网络是否可用
     */
    @Override
    public void onStart() {
        checkNetWork();
        super.onStart();

    }

    /**
     * 检查是否有网络
     */
    private void checkNetWork() {
        if (!NetworkUtil.isNetworkAvailable(getActivity())) {
            showSetNetworkUI(getActivity());
            showToastShort("获取数据失败");
            mDialog.dismiss();
            mRlFragmentMySee.setClickable(false);
            mIvUserFragmentAvatar.setClickable(false);
            mRlFragmentMyCollection.setClickable(false);
            mTvFragmentCopy.setVisibility(View.INVISIBLE);
            mRlFragmentMyFeedback.setClickable(false);
            rlmRlFragmentMyMessageNotice.setClickable(false);
            mRlFragmentMySetting.setClickable(false);
        } else {
            Log.e("lixiaofei", "onStart: " + "网络可用");
        }
    }

    /**
     * 弹出网络设置
     *
     * @param context 上下文
     */
    public void showSetNetworkUI(final Context context) {
        // 提示对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("网络设置提示")
                .setMessage("网络连接不可用,是否进行设置?")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = null;
                        // 判断手机系统的版本 即API大于10 就是3.0或以上版本
                        if (Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(
                                    Settings.ACTION_WIFI_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        context.startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 获取用户个人信息
     */
    private void getUserInfo() {
        OkGo.<String>get(MyConstant.GET_USER_INFO).params("token", SPUtils.getString(getActivity(), "token", ""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            Gson gson = new Gson();
                            GetUserInfoBean getUserInfoBean = gson.fromJson(s, GetUserInfoBean.class);
                            switch (getUserInfoBean.getCode()) {
                                case 1:
                                    if (rlFragmentMyUserInfo != null) {
                                        rlFragmentMyUserInfo.setVisibility(View.VISIBLE);
                                    }
                                    tvFragmentMyLogin.setVisibility(View.GONE);
                                    mRlFragmentMySee.setClickable(true);
                                    mIvUserFragmentAvatar.setClickable(true);
                                    mRlFragmentMyCollection.setClickable(true);
                                    mTvFragmentCopy.setVisibility(View.VISIBLE);
                                    mRlFragmentMyFeedback.setClickable(true);
                                    rlmRlFragmentMyMessageNotice.setClickable(true);
                                    mRlFragmentMySetting.setClickable(true);
                                    if (token == null || token.equals("")) {
                                        Glide.with(getActivity()).load(R.mipmap.mine_head_portrait).into(mIvUserFragmentAvatar);
                                        tvFragmentMyLogin.setText(R.string.fragment_my_login);
                                    } else {
                                        Glide.with(getActivity()).load(getUserInfoBean.getData().getIcon_file()).into(mIvUserFragmentAvatar);
                                        mTvUserFragmentName.setText(getUserInfoBean.getData().getName());
                                        mTvFragmentMyId.setText("ID:" + SPUtils.getString(getActivity(),"displayId",""));
                                        tvSummary.setText("简介：" + getUserInfoBean.getData().getSelf_intro());
                                    }
                                    mDialog.dismiss();
                                    break;
                                case -1002:
                                    showToastLong("请登录后操作");
                                    rlFragmentMyUserInfo.setVisibility(View.GONE);
                                    tvFragmentMyLogin.setVisibility(View.VISIBLE);
                                    tvFragmentMyLogin.setText("请登录");
                                    mDialog.dismiss();
                                    break;
                                case -1003:
                                    showToastLong("请登录后操作");
                                    rlFragmentMyUserInfo.setVisibility(View.GONE);
                                    tvFragmentMyLogin.setVisibility(View.VISIBLE);
                                    tvFragmentMyLogin.setText("请登录");
                                    mDialog.dismiss();
                                    break;
                                case -1004:
                                    rlFragmentMyUserInfo.setVisibility(View.GONE);
                                    tvFragmentMyLogin.setVisibility(View.VISIBLE);
                                    showToastLong("请登录后操作");
                                    tvFragmentMyLogin.setText("请登录");
                                    scFragmentMy.setChecked(true);
                                    mDialog.dismiss();
                                    break;
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            showToastLong(R.string.net_load_failed);
                        } finally {
                            mDialog.dismiss();
                        }
                    }
                });
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initData() {
        mDialog = new ProgressDialog(getContext());
        mDialog.setMessage(getResources().getString(R.string.wait));
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                //回退键监听
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
        getUserInfo();
        //获取模板更新通知状态
        getNotifyStutas();
    }

    /**
     * 获取模板通知状态
     */
    private void getNotifyStutas() {
        OkGo.<String>get(MyConstant.GET_NOTIFY).params("token", SPUtils.getString(getActivity(), "token", "")).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    Gson gson = new Gson();
                    GetNotifyStatusBean getNotifyStatusBean = gson.fromJson(s, GetNotifyStatusBean.class);
                    switch (getNotifyStatusBean.getCode()) {
                        case 1:
                            int is_notify = getNotifyStatusBean.getData().getIs_notify();
                            if (is_notify == 0) {
                                scFragmentMy.setChecked(false);
                            } else {
                                scFragmentMy.setChecked(true);
                            }
                            break;
                        case -1004:
                            scFragmentMy.setChecked(true);
//                            scFragmentMy.setEnabled(false);
                            break;
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    showToastShort(R.string.net_load_failed);
                }
            }
        });
    }

    /**
     * 上个页面的回调
     *
     * @param requestCode 请求码
     * @param resultCode  结果码
     * @param data        数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INFO_CODE && resultCode == RESULT_OK) {
            String name = data.getStringExtra("name");
            String intro = data.getStringExtra("intro");
            String url = data.getStringExtra("iconUrl");
            mTvUserFragmentName.setText(name);
            tvSummary.setText(intro);
            Glide.with(getActivity()).load(url).into(mIvUserFragmentAvatar);
        }
    }

    @Override
    protected void initEvent() {
        scFragmentMy.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (SPUtils.getString(getActivity(), "token", "").equals("")){
                    scFragmentMy.setChecked(true);
                }
                if (b) {
                    //开
                    modifyNotify(1);
                } else {
                    //关
                    modifyNotify(0);
                }
            }
        });
        mSmartRefreshLayoutFragmentMy.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getNotifyStutas();
                getUserInfo();
                refreshlayout.finishRefresh();
            }
        });
        mSmartRefreshLayoutFragmentMy.setEnableLoadmore(false);
    }

    /**
     * 修改更新模板状态信息
     *
     * @param i
     */
    private void modifyNotify(int i) {
        OkGo.<String>put(MyConstant.MODIFY_NOTIFY).params("token", SPUtils.getString(getActivity(), "token", ""))
                .params("is_notify", i).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Gson gson = new Gson();
                PostBean bean = gson.fromJson(s, PostBean.class);
                switch (bean.getCode()) {
                    case 1:
                        break;
                }

            }
        });

    }

    /**
     * 消息提醒界面
     */
    @OnClick(R.id.rl_fragment_my_message_notice)
    public void onRlmRlFragmentMyMessageNoticeClicked() {
        if (token == null || token.equals("")) {
            getLogin();
        } else {
            startActivity(new Intent(getActivity(), MessageNoticeActivity.class));
        }
    }

    private void getLogin() {
        startActivity(new Intent(getActivity(), LoginActivity.class));
        getActivity().finish();
    }

    /**
     * 我的收藏
     */
    @OnClick(R.id.rl_fragment_my_collection)
    public void onMRlFragmentMyCollectionClicked() {
        if (token == null || token.equals("")) {
            getLogin();
        } else {
            startActivity(new Intent(getActivity(), CollectionActivity.class));
        }

    }

    /**
     * 关于我们
     */
    @OnClick(R.id.rl_fragment_my_about)
    public void onMRlFragmentMyAboutClicked() {
        startActivity(new Intent(getActivity(), AboutActivity.class));
    }

    /**
     * 设置
     */
    @OnClick(R.id.rl_fragment_my_setting)
    public void onMRlFragmentMySettingClicked() {
        if (token == null || token.equals("")) {
            getLogin();
        } else {
            startActivity(new Intent(getActivity(), SettingActivity.class));
        }

    }

    /**
     * 我浏览过的
     */
    @OnClick(R.id.rl_fragment_my_see)
    public void onMRlFragmentMySeeClicked() {
        if (token == null || token.equals("")) {
            getLogin();
        } else {
            startActivity(new Intent(getActivity(), LookedActivity.class));
        }

    }

    /**
     * 意见反馈
     */
    @OnClick(R.id.rl_fragment_my_feedback)
    public void onMRlFragmentMyFeedbackClicked() {
        if (token == null || token.equals("")) {
            getLogin();
        } else {
            startActivity(new Intent(getActivity(), FeedbackActivity.class));
        }

    }

    /**
     * 点跳转个人信息
     */
    @OnClick(R.id.iv_user_fragment_avatar)
    public void onMIvUserFragmentAvatarClicked() {
        if (token == null || token.equals("")) {
            getLogin();
        } else {
            Intent intentInfo = new Intent(getActivity(), UserInfoActivity.class);
            startActivityForResult(intentInfo, INFO_CODE);
        }
    }

    /**
     * 点击复制
     */
    @OnClick(R.id.tv_fragment_copy)
    public void onMTvFragmentCopyClicked() {
        ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(SPUtils.getString(getActivity(),"displayId",""));
        showToastLong("复制成功!");
    }

}
